// 导出页面为PDF格式
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
export default {
  install(Vue) {
    Vue.prototype.getPdf = (sourceDiv, fileName, options) => {
      let { orientation, x, y } = options;
      html2Canvas(sourceDiv, {
        allowTaint: true,
        taintTest: false,
        useCORS: true,
        // width: 960,
        // height: 5072,
        dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
        scale: 4, // 按比例增加分辨率
      }).then((canvas) => {
        let contentWidth = canvas.width;
        let contentHeight = canvas.height;
        // pageHeight：换算一页a4纸的高度
        let pageHeight = (contentWidth / 592.28) * 841.89;
        // 切除边距后一页高度
        let cupPageHeight = (contentWidth / (592.28 - x * 2) * (841.89 - y * 2))
        if (orientation == "l") {
          pageHeight = (contentWidth / 841.89) * 592.28;
          cupPageHeight = (contentWidth / (841.89 - x * 2) * (592.28 - y * 2))
        }
        let leftHeight = contentHeight;
        // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽
        let imgWidth = 595.28 - x * 2;
        if (orientation == "l") {
          // 横向打印
          imgWidth = 841.89 - x * 2;
        }
        //按a4比例换算一页图像高度
        let imgHeight = (imgWidth / contentWidth) * contentHeight;
        let pageData = canvas.toDataURL("image/jpeg", 1.0);
        let PDF = new JsPDF(orientation, "pt", "a4");
        // 如果canvas的高度小于一页纸高度，直接生成图片
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, "JPEG", x, y, imgWidth, imgHeight);
        } else {
          let ctx = canvas.getContext("2d");
          let renderedHeight = 0; //已经渲染高度
          // 判断当前渲染高度是否小于需要渲染高度
          while (renderedHeight < leftHeight) {
            let page = document.createElement('canvas');
            page.width = contentWidth;
            page.height = Math.min(cupPageHeight, leftHeight - renderedHeight); //若内容不足一页，取最小值
            // 裁剪当前页需要渲染的内容，写入到新创建的canvas中
            page.getContext('2d')
                .putImageData(ctx.getImageData(0, renderedHeight, page.width, page.height),0 ,0);
            //  添加一页纸，将内容写入
            let oncePageData = page.toDataURL("image/jpeg", 1.0);
            //  添加图像到页面，保留x, y边距
            let onceImgHeight = imgWidth / page.width * page.height
            PDF.addImage(oncePageData, 'JPEG', x, y, imgWidth, onceImgHeight)
            renderedHeight += cupPageHeight;
            if(renderedHeight < leftHeight) {
              PDF.addPage();
            }
          }
        }
        PDF.save(fileName + ".pdf");
        return PDF;
      });
    };
  },
};
